package org.microsites.domain.dao.eod;

import java.util.List;

import net.lemnik.eodsql.BaseQuery;
import net.lemnik.eodsql.GeneratedKeys;
import net.lemnik.eodsql.Select;
import net.lemnik.eodsql.Update;

import org.microsites.domain.dao.HostDAO;
import org.microsites.domain.model.Host;
import org.microsites.util.EodDaoSupport;

public class HostDAOImpl extends EodDaoSupport implements HostDAO {
	private Query query;
	
	@Override
	public void create(Host entity) {
		entity.setId(getQuery().create(entity));
	}

	@Override
	public void delete(Long id) {
		getQuery().delete(id);
	}

	@Override
	public List<Host> list() {
		return getQuery().list();
	}

	@Override
	public List<Host> sublist(Long id) {
		return id == null ? getQuery().rootlist() : getQuery().sublist(id);
	}

	@Override
	public Host load(Long id) {
		return getQuery().load(id);
	}

	@Override
	public void update(Host entity) {
		getQuery().update(entity);
	}
	
	public Query getQuery() {
		if (query == null) query = super.getQuery(Query.class); 
		return query;
	}

	@Override
	public List<String> autocomplete(String column, String pattern) {
		return super.select(String.class, "SELECT " + column + " FROM Host WHERE " + column + " LIKE ?1 GROUP BY " + column, '%' + pattern + '%');
	}

	public interface Query extends BaseQuery {
		
		@Select(sql = "SELECT * FROM Host")
		public List<Host> list();
		
		@Select(sql = "SELECT * FROM Host WHERE [group]=?1")
		public List<Host> sublist(Long id);
		
		@Select(sql = "SELECT * FROM Host WHERE [group] IS NULL")
		public List<Host> rootlist();
		
		@Select(sql = "SELECT * FROM Host WHERE id=?1")
		public Host load(Long id);

        @Update(sql = "INSERT INTO Host (name,description,ip,url,os,osVersion,jvm,jvmPath,domain,admin,[group]) " +
        		"VALUES (?{1.name},?{1.description},?{1.ip},?{1.url},?{1.os},?{1.osVersion},?{1.jvm},?{1.jvmPath},?{1.domain},?{1.admin},?{1.group})",
                keys = GeneratedKeys.RETURNED_KEYS_FIRST_COLUMN)
		public Long create(Host h);
		
        @Update(sql = "UPDATE Host SET name=?{1.name},description=?{1.description},ip=?{1.ip},url=?{1.url},os=?{1.os}," +
        		"osVersion=?{1.osVersion},jvm=?{1.jvm},jvmPath=?{1.jvmPath},domain=?{1.domain},admin=?{1.admin},[group]=?{1.group} WHERE id=?{1.id}")
		public void update(Host h);
		
		@Update(sql = "DELETE FROM Host WHERE id=?1")
		public void delete(Long id);
	}

}
